package nc.pu.pub.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.framework.common.NCLocator;
import nc.itf.uap.pf.IplatFormEntry;
import nc.pub.cgdd.utils.util.JdbcUtil;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pp.util.StringUtils;
import nc.vo.pu.m21.entity.OrderHeaderVO;
import nc.vo.pu.m21.entity.OrderItemVO;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.AppContext;
import nc.ws.opm.pub.utils.result.APIErrCodeEnum;
import nccloud.api.pu.m21.IAPIPuOrderMaitain;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.openapi.scmpub.util.BillFieldsCodeToPkUtil;
import org.json.JSONString;
import uap.mw.trans.TransactionFactory;
import uap.mw.trans.UAPTransactionManagerProxy;
import uap.mw.trans.itf.IUAPTransactionManager;
import uap.mw.trans.util.TransactionContextType;
import uap.ws.rest.util.UAPRSConstance;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Path("/receive/order")
public class ReceivePoOrderResource extends AbstractReceiveOrderResource {
    private static String BODYTABLE = "po_order_b";
    private static String HEADTABLE = "po_order";
    @POST
    @Path("add")
    @Consumes(UAPRSConstance.MEDIATYPE_JSON)
    @Produces(UAPRSConstance.MEDIATYPE_JSON)
    public Object insert(Map<String, Object> params) {
        JSONObject jsonInfo= new JSONObject(params);
//        PuOrderResource ar =new PuOrderResource();
//        ar.approve(new String[]{"1001A210000000058EEQ"});
        this.getLogger().info("采购订单新增报文"+jsonInfo.toJSONString());
        JSONArray jsonArray = jsonInfo.getJSONArray("data");
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Map<String, Object> map = new HashMap<>();

            // 遍历JSONObject的键值对，添加到Map中
            java.util.Iterator<String> keys = jsonObject.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                Object value = jsonObject.get(key);
                map.put(key, value);
            }
            resultList.add(map);
        }
        JSONString save = save(resultList);
        this.getLogger().info("响应结果"+save.toJSONString());
        return save;
//return "1";
    }

    @Override
    public String getModule() {
        return "pu";
    }
    private JSONString save(List<Map<String, Object>> paramList){
        List<OrderVO> aggVOList = new ArrayList();
        OrderVO[] savevo = null;
        JSONObject result = new  JSONObject();
        try {
            Iterator var4 = paramList.iterator();
            while(var4.hasNext()) {
                Map<String, Object> map = (Map)var4.next();
                if (!map.containsKey(HEADTABLE) || !map.containsKey(BODYTABLE)) {
                    return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", APIErrCodeEnum.BUSINESSEXCCODE.getCode());
                }
                Map<String, String> headInfo = (Map)map.get(HEADTABLE);
                List<Map<String, String>> bodyInfo = (List)map.get(BODYTABLE);
                OrderVO aggvo = new OrderVO();
                OrderHeaderVO hvo = new OrderHeaderVO();
                hvo.setAttributeValue("pk_group", AppContext.getInstance().getPkGroup());
                Iterator var10 = headInfo.keySet().iterator();
                while(var10.hasNext()) {
                    String headkey = (String)var10.next();
                    hvo.setAttributeValue(headkey, headInfo.get(headkey));
                }
                String org = JdbcUtil.queryColumn("org_orgs", "pk_org", "code", hvo.getPk_org());
                hvo.setForderstatus(0);
                aggvo.setHVO(hvo);
                List<OrderItemVO> bvoList = new ArrayList();
                Iterator var19 = bodyInfo.iterator();
                while(var19.hasNext()) {
                    Map<String, String> bodyMap = (Map)var19.next();
                    OrderItemVO bvo = new OrderItemVO();
                    Iterator var14 = bodyMap.keySet().iterator();
                    if(StringUtils.isEmpty(bodyMap.get("pk_recvstordoc"))){
                        bodyMap.put("pk_recvstordoc","01");
                    };
                    while(var14.hasNext()) {
                        String bodykey = (String)var14.next();
                        bvo.setAttributeValue(bodykey, bodyMap.get(bodykey));
                    }
                        String sql ="select pk_stordoc from bd_stordoc where code ='%s'  and pk_org='%s' and dr =0";
                        //  仓库翻译
                        String stordoc = JdbcUtil.queryColumn(String.format(sql,bvo.getPk_recvstordoc(),org));
                        bvo.setPk_recvstordoc(stordoc);
                        if(StringUtils.isEmpty(stordoc))
                           throw new BusinessException("仓库编码翻译错误 请检查传入的仓库信息");

                    String materialsql ="select pk_material from bd_material_v where code ='%s'  and dr =0";
                    //  物料
                    String materiald = JdbcUtil.queryColumn(String.format(materialsql,bvo.getPk_material()));
//
                    if(StringUtils.isEmpty(materiald))
                        throw new BusinessException(String.format("物料编码翻译错误[%s] 请检查传入的物料信息",bvo.getPk_material()));
                    bvoList.add(bvo);
                }
                aggvo.setBVO(bvoList.toArray(new OrderItemVO[bvoList.size()]));
                aggVOList.add(aggvo);
            }
            OrderVO[] proinVOs = aggVOList.toArray(new OrderVO[aggVOList.size()]);
            BillFieldsCodeToPkUtil.doTranslateVOFields(proinVOs);
            IAPIPuOrderMaitain lookup = NCLocator.getInstance().lookup(IAPIPuOrderMaitain.class);
             savevo = lookup.save(proinVOs);
            IplatFormEntry iplat = NCLocator.getInstance().lookup(IplatFormEntry.class);
            for (OrderVO orderVO : savevo) {
                result.put(orderVO.getHVO().getVbillcode(),"保存成功->主键"+orderVO.getHVO().getPk_order());
                try{
                    OrderVO[] approve1 = (OrderVO[]) iplat.processAction("APPROVE","21", null, orderVO, null, null);
                }catch(Exception var16){
                    //审批没有通过 删除单据
                    lookup.delete(savevo);
                    return  ResultMessageUtil.exceptionToJSON(var16);
                }
            }
            this.getLogger().info(result.toJSONString());

            return ResultMessageUtil.toJSON(savevo, NCLangRes4VoTransl.getNCLangRes().getStrByID("4004100_0", "04004100-0156"));
        } catch (Exception var16) {
            return ResultMessageUtil.exceptionToJSON(var16);
        }



    }


    /**
     *   手动提交事务
     * update by yj 20231018
     * @return
     * @throws Exception
     */
    public boolean checkTransaction() throws Exception {
        IUAPTransactionManager manager = UAPTransactionManagerProxy.getCurTransManager();
        if (TransactionContextType.NULL.equals(manager.getTranContext().getTransType())) {
            return true;
        } else if (TransactionContextType.SOURCE.equals(manager.getTranContext().getTransType())) {
            if (manager.getTranContext().needRBPoint()) {
                return true;
            }
            TransactionFactory.getTMProxy().end(null);
        } else if (TransactionContextType.JOINED.equals(manager.getTranContext().getTransType())) {
            if (manager.getTranContext().needRBPoint()) {
                return true;
            }
            TransactionFactory.getTMProxy().end(null);
            checkTransaction();
        }
        return false;
    }


}
